//
//  HMChangePasswordController.m
//  HMMarket
//
//  Created by 孙鹏飞 on 2017/5/17.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMChangePasswordController.h"

@interface HMChangePasswordController ()

@property (weak, nonatomic) IBOutlet UIButton *changeBtn;

@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *npw;
@property (weak, nonatomic) IBOutlet UITextField *npwd;

@end

@implementation HMChangePasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"修改密码";
    [self setupView];
}

- (IBAction)changeBtnClicked:(id)sender
{
    if (![self checkForm]) {
        return;
    }
    
    // 1.上传参数
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObjOrNil:[MGAccountTool getUid] forKey:@"uid"];
    [param setObjOrNil:self.password.text forKey:@"oldPw"];
    [param setObjOrNil:self.npw.text forKey:@"newPw"];
    
    // 2.请求数据
    [HttpBaseTool post:kNewPasswordUrl params:param success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue]== 200) {
            [HMHUDManager showHUDWithText:@"密码修改成功"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [HMHUDManager showHUDWithText:@"密码修改失败"];
        }
    } failure:^(NSError *error) {
        [HMHUDManager showHUDWithText:@"密码修改失败"];
    }];
}

- (BOOL)checkForm
{
    BOOL registerEnabled = YES;
    NSUInteger npwLength = self.npw.text.length;
    NSUInteger passwordLength = self.password.text.length;
    
    NSString * errorMsg;
    
    if (passwordLength == 0) {
        errorMsg = @"请输入密码";
        registerEnabled = NO;
    } else if (passwordLength < 6) {
        errorMsg = @"密码长度不得小于6位";
        registerEnabled = NO;
    } else if (passwordLength > 16) {
        errorMsg = @"密码长度不得大于16位";
        registerEnabled = NO;
    } if (npwLength == 0) {
        errorMsg = @"请输入密码";
        registerEnabled = NO;
    } else if (npwLength < 6) {
        errorMsg = @"密码长度不得小于6位";
        registerEnabled = NO;
    } else if (npwLength > 16) {
        errorMsg = @"密码长度不得大于16位";
        registerEnabled = NO;
    } else if (![self.npw.text isEqualToString:self.npwd.text]) {
        errorMsg = @"两次输入密码不一致";
        registerEnabled = NO;
    }
    
    if(!registerEnabled && [errorMsg length] > 0){
        [HMHUDManager showHUDWithText:errorMsg];
    }
    return registerEnabled;
}

- (void)setupView
{
    [self configButton:_changeBtn borderWidth:0 borderColor:nil];
}

- (void)configButton:(UIButton *)button  borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
{
    button.layer.cornerRadius = 5;
    button.layer.masksToBounds = YES;
    button.layer.borderWidth = borderWidth;
    button.layer.borderColor = [borderColor CGColor];
}

@end
